package com.chanyachting.emall.action.productimage;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.chanyachting.emall.domain.Channel;
import com.chanyachting.emall.domain.Companyproduct;
import com.chanyachting.emall.domain.Productimage;
import com.chanyachting.emall.form.ShowProductimageForm;
import com.chanyachting.emall.service.ChannelService;
import com.chanyachting.emall.service.ProductImageService;
import com.chanyachting.emall.serviceImpl.ChannelServiceImpl;
import com.chanyachting.emall.serviceImpl.ProductImageServiceImpl;

public class QueryProductImageAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		ShowProductimageForm showPForm = (ShowProductimageForm) form;
		ProductImageService pimageService = new ProductImageServiceImpl();
		ChannelService cService = new ChannelServiceImpl();
		
		Integer productId = showPForm.getProductId();
		Companyproduct cproduct = new Companyproduct();
		cproduct.setId(productId);

		int channelId = showPForm.getChannelId();
		
		Integer subChannelId = showPForm.getSubChannelId();
		if (subChannelId == null) {
			return mapping.findForward("error");
		}
		Channel c = new Channel(channelId);
		List<Channel> subChannelList = cService.getSubChannel(c);
		
		if (subChannelList == null || subChannelList.size() == 0) {
			return mapping.findForward("error");
		}
		//判断指定的sub频道是否存在
		boolean isExistSubChannel = false;
		for(Channel cn:subChannelList) {
			if (cn == null || cn.getId() == null) {
				continue;
			}
			if (cn.getId().equals(subChannelId)) {
				showPForm.setSubChannelName(cn.getName());
				isExistSubChannel = true;
				break;
			}
		}
		showPForm.setChannelName(c.getName());
		if (isExistSubChannel == false) {
			return mapping.findForward("error");
		}
		
		List<Productimage> pimageList = pimageService.getProductimageByProduct(cproduct);
		
		if (pimageList == null || pimageList.size() == 0) {
			return mapping.findForward("error");
		}	
		
		List<Productimage> tmpImage = new ArrayList<Productimage>();
		for(int i=0;i<tmpImage.size();i++) {
			boolean afterY = false;
			if (i == 0 && "Y".equals(tmpImage.get(i).getIsdefaul())) {
				tmpImage = pimageList;
				break;
			} else {
				if ("Y".equals(tmpImage.get(i).getIsdefaul())) {
					tmpImage.add(0, pimageList.get(i));
					afterY = true;
				} else if(afterY) {
					tmpImage.add(i,pimageList.get(i));
				} else {
					tmpImage.add(i + 1,pimageList.get(i + 1));
				}
			}
		}

		showPForm.setPimageList(pimageList);
		showPForm.setSubChannelList(subChannelList);
		
		return mapping.findForward("productImageList");
	}
}
